<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="referrer" content="same-origin">
<meta name="referrer" content="no-referrer" />








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Netty之旅," />










<meta name="description" content="概览&amp;emsp;&amp;emsp;ChannelHandler应该是用户使用netty接触最多的组件，他的继承类也比较多，子类实现功能多不胜数，所以只列下一些基类，如下：&amp;emsp;&amp;emsp;根据事件在ChannelPipline中的流向，ChannelHandler按照出入站将事件分为两类，ChannelInboundHandler和ChannelOutboundHandler。">
<meta name="keywords" content="Netty之旅">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty之旅（十一）ChannelHandler">
<meta property="og:url" content="http://yoursite.com/2018/09/25/Netty之旅（十一）ChannelHandler/index.html">
<meta property="og:site_name" content="矩阵编程">
<meta property="og:description" content="概览&amp;emsp;&amp;emsp;ChannelHandler应该是用户使用netty接触最多的组件，他的继承类也比较多，子类实现功能多不胜数，所以只列下一些基类，如下：&amp;emsp;&amp;emsp;根据事件在ChannelPipline中的流向，ChannelHandler按照出入站将事件分为两类，ChannelInboundHandler和ChannelOutboundHandler。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/639cfad5gy1fv33xjyn28j212u0i8q4u.jpg">
<meta property="og:updated_time" content="2019-10-24T16:22:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Netty之旅（十一）ChannelHandler">
<meta name="twitter:description" content="概览&amp;emsp;&amp;emsp;ChannelHandler应该是用户使用netty接触最多的组件，他的继承类也比较多，子类实现功能多不胜数，所以只列下一些基类，如下：&amp;emsp;&amp;emsp;根据事件在ChannelPipline中的流向，ChannelHandler按照出入站将事件分为两类，ChannelInboundHandler和ChannelOutboundHandler。">
<meta name="twitter:image" content="http://ww1.sinaimg.cn/large/639cfad5gy1fv33xjyn28j212u0i8q4u.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/09/25/Netty之旅（十一）ChannelHandler/"/>





  <title>Netty之旅（十一）ChannelHandler | 矩阵编程</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7d29e6fba8e07d1a8af2414a20e5f2a6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">矩阵编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-主页"></i> <br />
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-分类"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-所有文章">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-文章"></i> <br />
            
            所有文章
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/09/25/Netty之旅（十一）ChannelHandler/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="matrix">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="矩阵编程">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty之旅（十一）ChannelHandler</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-25T16:41:05+08:00">
                2018-09-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Netty之旅/" itemprop="url" rel="index">
                    <span itemprop="name">Netty之旅</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/09/25/Netty之旅（十一）ChannelHandler/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/09/25/Netty之旅（十一）ChannelHandler/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="概览"><a href="#概览" class="headerlink" title="概览"></a>概览</h3><p>&emsp;&emsp;ChannelHandler应该是用户使用netty接触最多的组件，他的继承类也比较多，子类实现功能多不胜数，所以只列下一些基类，如下：<br><img src="http://ww1.sinaimg.cn/large/639cfad5gy1fv33xjyn28j212u0i8q4u.jpg" alt><br>&emsp;&emsp;根据事件在ChannelPipline中的流向，ChannelHandler按照出入站将事件分为两类，ChannelInboundHandler和ChannelOutboundHandler。<br><a id="more"></a><br>ChannelInboundHandler是对进站的数据进行处理，如<strong>channelRead()</strong>、<strong>channelReadComplete()</strong>等。ChannelOutboundHandler是处理出站的数据，如<strong>write()</strong>、<strong>flush()</strong>等。由<strong>Netty之旅（十）ChannelHandlerContext</strong>可知ChannelHandler之间是一个链式结构（由ChannelHandlerContext包裹着），每一个ChannelHandler接收并处理完事件后，再交给下一个ChannelHandler拦截处理。ChannelHandler很简单，只有三个方法：</p>
<ol>
<li><strong>handlerAdded</strong> 当handler被添加到ChannelPipline中调用</li>
<li><strong>handlerRemoved</strong> 当handler从ChannelPipline中移除时调用</li>
<li><strong>exceptionCaught</strong> ChannelPipline处理事件时出现错误时调用</li>
<li><strong>@Sharable</strong> 被标记为Sharable的ChannelHandler表示可以被多个Channel共享，需要用户保证线程安全。</li>
</ol>
<p>&emsp;&emsp;ChannelHandlerAdapter是一个适配器。因为ChannelHandler有一系列的事件，通常我们只关心其中的几个，使用ChannelHandlerAdapter可以选择性地实现我们感兴趣的事件。SimpleChannelInboundHandler在ChannelInboundHandlerAdapter之上又封装了一下，可以通过实现<strong>channelRead0()</strong>来处理特定的入站事件。通过ChannelHandler可以实现很多功能，我选择了下面几个具有代表性的子类进行探讨，这样我们对于整个ChannelHandler家族也会有更加深入的理解：</p>
<ol>
<li>MessageToByteEncoder 编码器</li>
<li>ByteToMessageDecoder 解码器</li>
<li>IdleStateHandler 心跳</li>
</ol>
<h3 id="MessageToByteEncoder"><a href="#MessageToByteEncoder" class="headerlink" title="MessageToByteEncoder"></a>MessageToByteEncoder</h3><p>&emsp;&emsp;MessageToByteEncoder是将我们自己的对象编码成为ByteBuf，先来看一下example里面一个例子：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NumberEncoder</span> <span class="keyword">extends</span> <span class="title">MessageToByteEncoder</span>&lt;<span class="title">Number</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">encode</span><span class="params">(ChannelHandlerContext ctx, Number msg, ByteBuf out)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Convert to a BigInteger first for easier implementation.</span></span><br><span class="line">        BigInteger v;</span><br><span class="line">        <span class="keyword">if</span> (msg <span class="keyword">instanceof</span> BigInteger) &#123;</span><br><span class="line">            v = (BigInteger) msg;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            v = <span class="keyword">new</span> BigInteger(String.valueOf(msg));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Convert the number into a byte array.</span></span><br><span class="line">        <span class="keyword">byte</span>[] data = v.toByteArray();</span><br><span class="line">        <span class="keyword">int</span> dataLength = data.length;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Write a message.</span></span><br><span class="line">        out.writeByte((<span class="keyword">byte</span>) <span class="string">'F'</span>); <span class="comment">// magic number</span></span><br><span class="line">        out.writeInt(dataLength);  <span class="comment">// data length</span></span><br><span class="line">        out.writeBytes(data);      <span class="comment">// data</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>通过实现<strong>encode()</strong>的方法，就将Number数据写入到了ByteBuf中。<strong>encode()</strong>在MessageToByteEncoder中通过<strong>write()</strong>方法调用：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ByteBuf buf = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (acceptOutboundMessage(msg)) &#123;</span><br><span class="line">            <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">            I cast = (I) msg;</span><br><span class="line">            buf = allocateBuffer(ctx, cast, preferDirect);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                encode(ctx, cast, buf);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                ReferenceCountUtil.release(cast);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (buf.isReadable()) &#123;</span><br><span class="line">                ctx.write(buf, promise);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                buf.release();</span><br><span class="line">                ctx.write(Unpooled.EMPTY_BUFFER, promise);</span><br><span class="line">            &#125;</span><br><span class="line">            buf = <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ctx.write(msg, promise);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (EncoderException e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> e;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> EncoderException(e);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (buf != <span class="keyword">null</span>) &#123;</span><br><span class="line">            buf.release();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>acceptOutboundMessage() 判断该事件是不是当前类感兴趣的事件，比如NumberEncoder类会判断msg是否是Number类型。</li>
<li>preferDirect参数来决定allocateBuffer()分配堆还是直接内存，msg写入ByteBuf中后，调用ReferenceCountUtil释放引用。</li>
<li>如果缓冲区有可发送的字节，则调用ChannelHandlerContext的write写入ByteBuf；如果无可发送字节，写入一个空的ByteBuf</li>
</ol>
<h3 id="ByteToMessageDecoder"><a href="#ByteToMessageDecoder" class="headerlink" title="ByteToMessageDecoder"></a>ByteToMessageDecoder</h3><p>&emsp;&emsp;ByteToMessageDecoder是将ByteBuf转换为我们熟知的对象，还是通过example来看一下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BigIntegerDecoder</span> <span class="keyword">extends</span> <span class="title">ByteToMessageDecoder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Wait until the length prefix is available.</span></span><br><span class="line">        <span class="keyword">if</span> (in.readableBytes() &lt; <span class="number">5</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        in.markReaderIndex();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Check the magic number.</span></span><br><span class="line">        <span class="keyword">int</span> magicNumber = in.readUnsignedByte();</span><br><span class="line">        <span class="keyword">if</span> (magicNumber != <span class="string">'F'</span>) &#123;</span><br><span class="line">            in.resetReaderIndex();</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CorruptedFrameException(<span class="string">"Invalid magic number: "</span> + magicNumber);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Wait until the whole data is available.</span></span><br><span class="line">        <span class="keyword">int</span> dataLength = in.readInt();</span><br><span class="line">        <span class="keyword">if</span> (in.readableBytes() &lt; dataLength) &#123;</span><br><span class="line">            in.resetReaderIndex();</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Convert the received data into a new BigInteger.</span></span><br><span class="line">        <span class="keyword">byte</span>[] decoded = <span class="keyword">new</span> <span class="keyword">byte</span>[dataLength];</span><br><span class="line">        in.readBytes(decoded);</span><br><span class="line"></span><br><span class="line">        out.add(<span class="keyword">new</span> BigInteger(decoded));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个例子解码以魔数F开头，包含一个integer数据长度，最后是数据BigInteger的实例。比如{ ‘F’, 0, 0, 0, 1, 42 }会解码为new BigInteger(42)。先看一下ByteToMessageDecoder中的<strong>channelRead()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (msg <span class="keyword">instanceof</span> ByteBuf) &#123;</span><br><span class="line">            CodecOutputList out = CodecOutputList.newInstance();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                ByteBuf data = (ByteBuf) msg;</span><br><span class="line">                first = cumulation == <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">if</span> (first) &#123;</span><br><span class="line">                    cumulation = data;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data);</span><br><span class="line">                &#125;</span><br><span class="line">                callDecode(ctx, cumulation, out);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (DecoderException e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> e;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> DecoderException(e);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (cumulation != <span class="keyword">null</span> &amp;&amp; !cumulation.isReadable()) &#123;</span><br><span class="line">                    numReads = <span class="number">0</span>;</span><br><span class="line">                    cumulation.release();</span><br><span class="line">                    cumulation = <span class="keyword">null</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (++ numReads &gt;= discardAfterReads) &#123;</span><br><span class="line">                    <span class="comment">// We did enough reads already try to discard some bytes so we not risk to see a OOME.</span></span><br><span class="line">                    <span class="comment">// See https://github.com/netty/netty/issues/4275</span></span><br><span class="line">                    numReads = <span class="number">0</span>;</span><br><span class="line">                    discardSomeReadBytes();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">int</span> size = out.size();</span><br><span class="line">                decodeWasNull = !out.insertSinceRecycled();</span><br><span class="line">                fireChannelRead(ctx, out, size);</span><br><span class="line">                out.recycle();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ctx.fireChannelRead(msg);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>先判断是否是ByteBuf类型的msg，否则无需处理；判断cumulation是否为空，为空则直接将msg赋值给他，不为空，证明上次还有消息未被处理完毕，使用Cumulator进行赋值。看一下Cumulator做了什么：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Cumulator MERGE_CUMULATOR = <span class="keyword">new</span> Cumulator() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> ByteBuf <span class="title">cumulate</span><span class="params">(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">final</span> ByteBuf buffer;</span><br><span class="line">            <span class="keyword">if</span> (cumulation.writerIndex() &gt; cumulation.maxCapacity() - in.readableBytes()</span><br><span class="line">                    || cumulation.refCnt() &gt; <span class="number">1</span> || cumulation.isReadOnly()) &#123;</span><br><span class="line">                <span class="comment">// Expand cumulation (by replace it) when either there is not more room in the buffer</span></span><br><span class="line">                <span class="comment">// or if the refCnt is greater then 1 which may happen when the user use slice().retain() or</span></span><br><span class="line">                <span class="comment">// duplicate().retain() or if its read-only.</span></span><br><span class="line">                <span class="comment">//</span></span><br><span class="line">                <span class="comment">// See:</span></span><br><span class="line">                <span class="comment">// - https://github.com/netty/netty/issues/2327</span></span><br><span class="line">                <span class="comment">// - https://github.com/netty/netty/issues/1764</span></span><br><span class="line">                buffer = expandCumulation(alloc, cumulation, in.readableBytes());</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                buffer = cumulation;</span><br><span class="line">            &#125;</span><br><span class="line">            buffer.writeBytes(in);</span><br><span class="line">            in.release();</span><br><span class="line">            <span class="keyword">return</span> buffer;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br></pre></td></tr></table></figure></p>
<p>如果当前cumulation（ByteBuf）容量不够或者引用计数大于1或者只读，<strong>expandCumulation()</strong>新建一个ByteBuf代替：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> ByteBuf <span class="title">expandCumulation</span><span class="params">(ByteBufAllocator alloc, ByteBuf cumulation, <span class="keyword">int</span> readable)</span> </span>&#123;</span><br><span class="line">    ByteBuf oldCumulation = cumulation;</span><br><span class="line">    cumulation = alloc.buffer(oldCumulation.readableBytes() + readable);</span><br><span class="line">    cumulation.writeBytes(oldCumulation);</span><br><span class="line">    oldCumulation.release();</span><br><span class="line">    <span class="keyword">return</span> cumulation;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>好了Cumulator操作到此结束，回过头继续看channelRead()的<strong>callDecode()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">callDecode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (in.isReadable()) &#123;</span><br><span class="line">            <span class="keyword">int</span> outSize = out.size();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (outSize &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                fireChannelRead(ctx, out, outSize);</span><br><span class="line">                out.clear();</span><br><span class="line"></span><br><span class="line">                <span class="comment">// Check if this handler was removed before continuing with decoding.</span></span><br><span class="line">                <span class="comment">// If it was removed, it is not safe to continue to operate on the buffer.</span></span><br><span class="line">                <span class="comment">//</span></span><br><span class="line">                <span class="comment">// See:</span></span><br><span class="line">                <span class="comment">// - https://github.com/netty/netty/issues/4635</span></span><br><span class="line">                <span class="keyword">if</span> (ctx.isRemoved()) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                outSize = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">int</span> oldInputLength = in.readableBytes();</span><br><span class="line">            decodeRemovalReentryProtection(ctx, in, out);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Check if this handler was removed before continuing the loop.</span></span><br><span class="line">            <span class="comment">// If it was removed, it is not safe to continue to operate on the buffer.</span></span><br><span class="line">            <span class="comment">//</span></span><br><span class="line">            <span class="comment">// See https://github.com/netty/netty/issues/1664</span></span><br><span class="line">            <span class="keyword">if</span> (ctx.isRemoved()) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (outSize == out.size()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (oldInputLength == in.readableBytes()) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (oldInputLength == in.readableBytes()) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> DecoderException(</span><br><span class="line">                        StringUtil.simpleClassName(getClass()) +</span><br><span class="line">                                <span class="string">".decode() did not read anything but decoded a message."</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (isSingleDecode()) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (DecoderException e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> e;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception cause) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> DecoderException(cause);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">decodeRemovalReentryProtection</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    decodeState = STATE_CALLING_CHILD_DECODE;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        decode(ctx, in, out);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">boolean</span> removePending = decodeState == STATE_HANDLER_REMOVED_PENDING;</span><br><span class="line">        decodeState = STATE_INIT;</span><br><span class="line">        <span class="keyword">if</span> (removePending) &#123;</span><br><span class="line">            handlerRemoved(ctx);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>循环解码ByteBuf，拿到List<object> out的原始大小和<strong>decodeRemovalReentryProtection()</strong>解码完成后的大小比较：</object></p>
<ol>
<li>如果解码后out大小未变，判断ByteBuf的可读大小有没有变化，如果没变化，证明此消息无法满足业务数据，退出等待I/O继续读取。</li>
<li>如果解码后out大小未变，但是ByteBuf的可读大小有了变化，那证明业务正在转换，循环continue。</li>
<li>如果解码后out大小变化了，但是ByteBuf的可读大小没有变化，netty就会抛出DecoderException异常，这也是业务处理需要注意的地方。</li>
</ol>
<h3 id="IdleStateHandler"><a href="#IdleStateHandler" class="headerlink" title="IdleStateHandler"></a>IdleStateHandler</h3><p>&emsp;&emsp;IdleStateHandler是netty的心跳机制，继承自ChannelDuplexHandler，ChannelDuplexHandler同时实现了ChannelInboundHandler和ChannelOutboundHandler，是一个双向的事件处理器。看一下IdleStateHandler的初始化方法<strong>initialize()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initialize</span><span class="params">(ChannelHandlerContext ctx)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Avoid the case where destroy() is called before scheduling timeouts.</span></span><br><span class="line">    <span class="comment">// See: https://github.com/netty/netty/issues/143</span></span><br><span class="line">    <span class="keyword">switch</span> (state) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    state = <span class="number">1</span>;</span><br><span class="line">    initOutputChanged(ctx);</span><br><span class="line"></span><br><span class="line">    lastReadTime = lastWriteTime = ticksInNanos();</span><br><span class="line">    <span class="keyword">if</span> (readerIdleTimeNanos &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        readerIdleTimeout = schedule(ctx, <span class="keyword">new</span> ReaderIdleTimeoutTask(ctx),</span><br><span class="line">                readerIdleTimeNanos, TimeUnit.NANOSECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (writerIdleTimeNanos &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        writerIdleTimeout = schedule(ctx, <span class="keyword">new</span> WriterIdleTimeoutTask(ctx),</span><br><span class="line">                writerIdleTimeNanos, TimeUnit.NANOSECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (allIdleTimeNanos &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        allIdleTimeout = schedule(ctx, <span class="keyword">new</span> AllIdleTimeoutTask(ctx),</span><br><span class="line">                allIdleTimeNanos, TimeUnit.NANOSECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>主要是初始化三个任务，ReaderIdleTimeoutTask读空闲超时检测，WriterIdleTimeoutTask写空闲超时检测，AllIdleTimeoutTask全事件空闲超时检测。看一下ReaderIdleTimeoutTask的核心处理方法<strong>run()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(ChannelHandlerContext ctx)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> nextDelay = readerIdleTimeNanos;</span><br><span class="line">    <span class="keyword">if</span> (!reading) &#123;</span><br><span class="line">        nextDelay -= ticksInNanos() - lastReadTime;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (nextDelay &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// Reader is idle - set a new timeout and notify the callback.</span></span><br><span class="line">        readerIdleTimeout = schedule(ctx, <span class="keyword">this</span>, readerIdleTimeNanos, TimeUnit.NANOSECONDS);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">boolean</span> first = firstReaderIdleEvent;</span><br><span class="line">        firstReaderIdleEvent = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            IdleStateEvent event = newIdleStateEvent(IdleState.READER_IDLE, first);</span><br><span class="line">            channelIdle(ctx, event);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            ctx.fireExceptionCaught(t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// Read occurred before the timeout - set a new timeout with shorter delay.</span></span><br><span class="line">        readerIdleTimeout = schedule(ctx, <span class="keyword">this</span>, nextDelay, TimeUnit.NANOSECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如果在规定的readerIdleTimeNanos时间内没有读事件（reading为false），触发<strong>channelIdle()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">channelIdle</span><span class="params">(ChannelHandlerContext ctx, IdleStateEvent evt)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ctx.fireUserEventTriggered(evt);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>ChannelHandlerContext会触发ChannlePipline上的ChannelInboundHandler的userEventTriggered事件，我们的ChannelInboundHandler可以在此方法上做一些写空闲超时的处理。再看下WriterIdleTimeoutTask的<strong>run()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(ChannelHandlerContext ctx)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">long</span> lastWriteTime = IdleStateHandler.<span class="keyword">this</span>.lastWriteTime;</span><br><span class="line">    <span class="keyword">long</span> nextDelay = writerIdleTimeNanos - (ticksInNanos() - lastWriteTime);</span><br><span class="line">    <span class="keyword">if</span> (nextDelay &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// Writer is idle - set a new timeout and notify the callback.</span></span><br><span class="line">        writerIdleTimeout = schedule(ctx, <span class="keyword">this</span>, writerIdleTimeNanos, TimeUnit.NANOSECONDS);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">boolean</span> first = firstWriterIdleEvent;</span><br><span class="line">        firstWriterIdleEvent = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (hasOutputChanged(ctx, first)) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            IdleStateEvent event = newIdleStateEvent(IdleState.WRITER_IDLE, first);</span><br><span class="line">            channelIdle(ctx, event);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            ctx.fireExceptionCaught(t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// Write occurred before the timeout - set a new timeout with shorter delay.</span></span><br><span class="line">        writerIdleTimeout = schedule(ctx, <span class="keyword">this</span>, nextDelay, TimeUnit.NANOSECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这里的逻辑大致和ReaderIdleTimeoutTask一样，不过有一点不一样，就是这个<strong>hasOutputChanged(ctx, first)</strong>，如果返回true，这里会直接判定非超时，看一下这个方法做了什么：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">hasOutputChanged</span><span class="params">(ChannelHandlerContext ctx, <span class="keyword">boolean</span> first)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (observeOutput) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// We can take this shortcut if the ChannelPromises that got passed into write()</span></span><br><span class="line">        <span class="comment">// appear to complete. It indicates "change" on message level and we simply assume</span></span><br><span class="line">        <span class="comment">// that there's change happening on byte level. If the user doesn't observe channel</span></span><br><span class="line">        <span class="comment">// writability events then they'll eventually OOME and there's clearly a different</span></span><br><span class="line">        <span class="comment">// problem and idleness is least of their concerns.</span></span><br><span class="line">        <span class="keyword">if</span> (lastChangeCheckTimeStamp != lastWriteTime) &#123;</span><br><span class="line">            lastChangeCheckTimeStamp = lastWriteTime;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// But this applies only if it's the non-first call.</span></span><br><span class="line">            <span class="keyword">if</span> (!first) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Channel channel = ctx.channel();</span><br><span class="line">        Unsafe unsafe = channel.unsafe();</span><br><span class="line">        ChannelOutboundBuffer buf = unsafe.outboundBuffer();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (buf != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> messageHashCode = System.identityHashCode(buf.current());</span><br><span class="line">            <span class="keyword">long</span> pendingWriteBytes = buf.totalPendingWriteBytes();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (messageHashCode != lastMessageHashCode || pendingWriteBytes != lastPendingWriteBytes) &#123;</span><br><span class="line">                lastMessageHashCode = messageHashCode;</span><br><span class="line">                lastPendingWriteBytes = pendingWriteBytes;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (!first) &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>observeOutput是构造函数的参数，默认为false。</li>
<li>检测lastChangeCheckTimeStamp和lastWriteTime是否一致，first即firstWriterIdleEvent（默认true），一次写事件完成标识为true，检测到空闲超时的时候会将firstWriterIdleEvent置为false。第一次超时进入hasOutputChanged(ChannelHandlerContext ctx, boolean first)，firstWriterIdleEvent为true。</li>
<li>检测messageHashCode和lastMessageHashCode是否一致，或者pendingWriteBytes和lastPendingWriteBytes是否一致。</li>
<li>整理下observeOutput的意义，在写空闲超时的时候，考虑当前写数据是否存在超时的情况，如果是写数据引起的超时，不会触发空闲超时。</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Netty之旅/" rel="tag"># Netty之旅</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/08/Netty之旅（十）ChannelHandlerContext/" rel="next" title="Netty之旅（十）ChannelHandlerContext">
                <i class="fa fa-chevron-left"></i> Netty之旅（十）ChannelHandlerContext
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/08/Netty之旅（十二）EventLoop/" rel="prev" title="Netty之旅（十二）EventLoop">
                Netty之旅（十二）EventLoop <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">matrix</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">47</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#概览"><span class="nav-number">1.</span> <span class="nav-text">概览</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MessageToByteEncoder"><span class="nav-number">2.</span> <span class="nav-text">MessageToByteEncoder</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ByteToMessageDecoder"><span class="nav-number">3.</span> <span class="nav-text">ByteToMessageDecoder</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IdleStateHandler"><span class="nav-number">4.</span> <span class="nav-text">IdleStateHandler</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">matrix</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
<div class=BbeiAn-info">
  浙ICP备 -
  <a href="http://www.beian.miit.gov.cn">18040498号</a>
  </a>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://luyun.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://yoursite.com/2018/09/25/Netty之旅（十一）ChannelHandler/';
          this.page.identifier = '2018/09/25/Netty之旅（十一）ChannelHandler/';
          this.page.title = 'Netty之旅（十一）ChannelHandler';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://luyun.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
